package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.RedisConstant;
import com.itheima.dao.SetmealDao;
import com.itheima.entity.PageResult;
import com.itheima.pojo.Setmeal;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import redis.clients.jedis.JedisPool;

import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service(interfaceClass = SetmealService.class)
@Transactional
public class SetmealServiceImpl implements SetmealService {

    @Autowired
    private SetmealDao setmealDao;

    @Autowired
    private JedisPool jedisPool;

    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;

    @Value("${out_put_path}")
    private String outputpath;


    @Override
    public Setmeal findById(Integer id) {
        return setmealDao.findById(id);
    }

    @Override
    public List<Map<String, Object>> findSetmealCount() {
        return setmealDao.findSetmealCount();
    }

    @Override
    public PageResult pageQuery(Integer currentPage, Integer pageSize, String queryString) {
        PageHelper.startPage(currentPage, pageSize);
        Page<Setmeal> page = setmealDao.selectByConditon(queryString);
        return new PageResult(page.getTotal(), page.getResult());
    }

    @Override
    public List<Setmeal> findAll() {
        return setmealDao.findAll();
    }


    //将图片信息存到redis的方法
    public void savePic2Redis(String pic) {
        jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES, pic);
    }

    @Override
    public void add(Setmeal setmeal, Integer[] checkgroupIds) {
        setmealDao.add(setmeal);
        if (checkgroupIds != null && checkgroupIds.length > 0) {
            setSetmealAndCheckGroup(setmeal.getId(), checkgroupIds);
        }
        //添加成功后调用方法将添加到数据库中的图片信息存储到redis
        try {
            savePic2Redis(setmeal.getImg());
        } catch (Exception e) {
            e.printStackTrace();
        }

        //新增套餐后重新生成静态页面
        generateMobileStaticHtml();

    }

    //生成静态页面的方法
    private void generateMobileStaticHtml() {

        //查询所有套餐
        List<Setmeal> setmealList = this.findAll();
        //调用生成套餐列表静态页面方法
        generateMobileSetmealListHtml(setmealList);
        //调用生成套餐详情静态页面方法
        generateMobileSetmealDetailHtml(setmealList);
    }


    //套餐列表静态页面生成方法
    private void generateMobileSetmealListHtml(List<Setmeal> setmealList) {
        Map<String, Object> map = new HashMap<>();
        map.put("setmealList", setmealList);
        this.generateHtml("mobile_setmeal.ftl", "m_setmeal.html", map);

    }

    //套餐详情静态页面生成方法
    private void generateMobileSetmealDetailHtml(List<Setmeal> setmealList) {

        for (Setmeal setmeal : setmealList) {
            Map<String, Object> map = new HashMap<>();
            map.put("setmeal", this.findById(setmeal.getId()));
            this.generateHtml("mobile_setmeal_detail.ftl", "setmeal_detail_" + setmeal.getId() + ".html", map);
        }
    }


    /**
     * 生成html静态页面方法
     * @param templateName 模版名
     * @param htmlPageName 页面名
     * @param map 参数
     */
    private void generateHtml(String templateName, String htmlPageName, Map<String, Object> map) {
        Configuration configuration = freeMarkerConfigurer.getConfiguration();
        Writer out = null;
        try {
            // 加载模版文件
            Template template = configuration.getTemplate(templateName);
            // 生成数据
            File docFile = new File(outputpath + "\\" + htmlPageName);
            out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(docFile),"utf-8"));
            // 输出文件
            template.process(map, out);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != out) {
                    out.flush();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }

    }


    /**
     * 设置套餐与检查组的关联(中间表添加数据)
     *
     * @param setmealId
     * @param checkgroupIds
     */
    public void setSetmealAndCheckGroup(Integer setmealId, Integer[] checkgroupIds) {
        //判断数组是否为空,不为空则添加数据
        if (checkgroupIds != null && checkgroupIds.length > 0) {
            //遍历添加关联数据
            for (Integer checkgroupId : checkgroupIds) {
                //使用map集合来设置参数
                Map<String, Integer> map = new HashMap();
                map.put("setmeal_id", setmealId);
                map.put("checkgroup_id", checkgroupId);
                //添加关联数据
                setmealDao.setCheckGroupAndCheckItem(map);
            }

        }
    }


}
